import React, { Component } from 'react';

interface AccordionPanelProps {
    head: JSX.Element | string | any;
    className?: string;
    headClickHandle: Function;
    show?: Boolean;
}

interface AccordionPanelState {
    show?: Boolean;
    showH: any;
}

class AccordionPanel extends Component<any, AccordionPanelState> {
    constructor(props: AccordionPanelProps) {
        super(props);
        this.state = {
            show: this.props.show,
            showH: ''
        };
    }

    static defaultProps = {
        headClickHandle: () => {}
    };

    listNode: any;

    componentDidMount() {
        setTimeout(() => {
            this.setState({ showH: this.listNode.offsetHeight });
        }, 0);
    }

    componentWillReceiveProps({ show }: any) {
        this.setState({ show });
    }

    render() {
        const { head, className, children } = this.props;
        const { show, showH } = this.state;
        const headNode = typeof head === 'function' ? head() : head;
        let height =
            !show && showH === '' ? showH : !show && showH !== '' ? 0 : showH;
        return (
            <div className={className}>
                <div onClick={e => this.props.headClickHandle(show)}>
                    {headNode}
                </div>
                <div
                    className="accordion-panel-list"
                    ref={listNode => {
                        this.listNode = listNode;
                    }}
                    style={{ height: `${height}px` }}
                >
                    {children}
                </div>
            </div>
        );
    }
}

export default AccordionPanel;
